package controller

import (
	"base/app/models"
	"github.com/gin-gonic/gin"
	"github.com/xuri/excelize/v2"
	"gorm.io/gorm"
	"strings"
)

type ManageCtl struct {
	db *gorm.DB
}

var Manage = ManageCtl{}

// 添加渔船
func (m *ManageCtl) AddFisherShip(c *gin.Context) {
	m.db = models.Db
	//	接受文件 .xlsx
	file, _ := c.FormFile("filePath")
	// 保存文件
	err := c.SaveUploadedFile(file, "./public/"+file.Filename)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "文件保存失败",
		})
		return
	}
	// 读取文件
	f, err := excelize.OpenFile("./public/" + file.Filename)
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "文件读取失败",
		})
		return
	}
	// 获取Sheet1
	rows, err := f.GetRows("Sheet1")
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "文件读取失败",
		})
		return
	}

	var fisherShips []models.FisherShip
	for _, row := range rows {
		if len(row) < 8 || !strings.Contains(row[1], "鲁") {
			continue
		}
		var fisherShip models.FisherShip
		fisherShip.Name = strings.ReplaceAll(row[1], " ", "")
		fisherShip.Owner = row[2]
		fisherShip.Kw = row[4]
		fisherShip.Length = row[3]
		fisherShip.MMSI = row[8]
		fisherShip.Northid = row[9]
		fisherShips = append(fisherShips, fisherShip)
	}

	//m.db.Create(&fisherShips)
	// Name字段唯一，如果有重复的就不插入
	for _, fisherShip := range fisherShips {
		m.db.Where("name = ?", fisherShip.Name).FirstOrCreate(&fisherShip)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}

//获取所有驳船
